package com.dqp.cslggroup.Library;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewStub;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;

import androidx.appcompat.widget.Toolbar;

import com.dqp.cslggroup.EventBus.MessageEvent;
import com.dqp.cslggroup.R;
import com.dqp.cslggroup.UI.BaseActivity;
import com.dqp.cslggroup.UI.MyApplication;
import com.dqp.cslggroup.Util.NetCheckUtil;
import com.dqp.cslggroup.Util.SharedPreferencesUtil;
import com.dqp.cslggroup.Util.StringUtil;
import com.dqp.cslggroup.Util.ToastUtil;
import com.dqp.cslggroup.Util.UiUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.Objects;


public class book_xj extends BaseActivity {
    private Map<String, String> cookie = null;
    private String use_url;
    private String[] Arry, xj, Arry_book;
    private String x, bar_code = null, check = null, captcha = null;
    private ListView listView;
    private String s, book;
    private static String bf;
    private long time;
    private Connection.Response response;
    private Document document;
    private ViewStub viewstub_loading;
    private ViewStub viewstub_null;
    private byte[] bytes;
    private String Authorization = SharedPreferencesUtil.getStringSp(MyApplication.getContext(), "Authorization", "");

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.jw_tip);
        EventBus.getDefault().register(this);
        Toolbar toolbar = findViewById(R.id.include_toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
        Intent intent = getIntent();
        cookie = (Map<String, String>) intent.getSerializableExtra("cookies");
        use_url = intent.getStringExtra("url");
        initCmp();
        if (NetCheckUtil.checkNet(book_xj.this))
            getBookList();
        else {
            EventBus.getDefault().post(new MessageEvent("book_xj", 6, null));
            ToastUtil.showToast("请连接网络！");
        }
    }

    private void initCmp() {
        listView = findViewById(R.id.tip_list);
        viewstub_loading = findViewById(R.id.viewstub_loading);
        viewstub_null = findViewById(R.id.viewstub_null_date);
    }


    @SuppressLint("HandlerLeak")
    public void getBookList() {
        new Thread(() -> {
            try {
                EventBus.getDefault().post(new MessageEvent("book_xj", 0, null));
                response = Jsoup.connect(use_url + "/reader/book_lst.php")
                        .ignoreContentType(true)
                        .cookies(cookie)
                        .header("Authorization", Authorization)
                        .userAgent("Mozilla")
                        .method(Connection.Method.GET)
                        .timeout(3000)
                        .execute();
                document = Jsoup.parse(response.body());
                s = document.select("input[title=renew]").toString();
                bf = s;
                book = document.select("td[class=whitetext]").text();
                if (!book.isEmpty()) {
                    Arry_book = book.trim().split("无  ");
                    EventBus.getDefault().post(new MessageEvent("book_xj", 3, null));
                } else {
                    EventBus.getDefault().post(new MessageEvent("book_xj", 6, null));
                }
            } catch (IOException e) {
                e.printStackTrace();
                EventBus.getDefault().post(new MessageEvent("book_xj", 4, null));
            }
        }).start();

        new LibPicThread().start();
    }

    public void xjData(int i) {
        s = bf;
        if (!s.isEmpty()) {
            Arry = s.trim().split(">");
            s = StringUtil.RemoveBrackets(Arry[i]);
            x = StringUtil.replaceString(s, "'", "");
            xj = x.trim().split(",");
        }
        bar_code = xj[0];
        check = xj[1];

    }

    public void putxj() {
        new Thread(() -> {
            try {
                time = new Date().getTime();
                response = Jsoup.connect(use_url + "/reader/ajax_renew.php" + "?bar_code=" + bar_code + "&check=" + check + "&captcha=" + captcha + "&time=" + time)
                        .ignoreContentType(true)
                        .cookies(cookie)
                        .header("Authorization", Authorization)
                        .userAgent("Mozilla")
                        .method(Connection.Method.GET)
                        .timeout(3000)
                        .execute();
                document = Jsoup.parse(response.body());
                ToastUtil.showToast(document.text());
            } catch (IOException e) {
                e.printStackTrace();
                EventBus.getDefault().post(new MessageEvent("book_xj", 5, null));
            }
        }).start();
    }


    public class LibPicThread extends Thread {
        @Override
        public void run() {
            Connection.Response response;
            try {
                response = Jsoup.connect(use_url + "/reader/captcha.php")
                        .cookies(cookie)
                        .ignoreContentType(true)
                        .userAgent("Mozilla")
                        .header("Authorization", Authorization)
                        .method(Connection.Method.GET)
                        .timeout(3000)
                        .execute();
                bytes = response.bodyAsBytes();
            } catch (IOException e) {
                e.printStackTrace();
                EventBus.getDefault().post(new MessageEvent("book_xj", 5, null));
                ToastUtil.showToast("当前网络不可用！");
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private void setImg(ImageView yz) {
        yz.setImageDrawable(null);
        ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
        yz.setImageDrawable(Drawable.createFromStream(stream, "fm"));
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.getEvent().equals("book_xj")) {
            switch (event.getWhat()) {
                case 1:
                    viewstub_loading.setVisibility(View.VISIBLE);
                    break;
                case 2:
                    viewstub_loading.setVisibility(View.GONE);
                    break;
                case 3:
                    ArrayAdapter arrayAdapter = new ArrayAdapter<>(book_xj.this, android.R.layout.simple_list_item_1, Arry_book);
                    listView.setAdapter(arrayAdapter);
                    listView.setOnItemClickListener((adapterView, view, i, l) -> {
                        final android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(book_xj.this);
                        @SuppressLint("InflateParams") View views = LayoutInflater.from(book_xj.this).inflate(R.layout.xj_yz, null);
                        builder.setView(views);
                        final EditText yzm = views.findViewById(R.id.xj_yz_yzm);
                        Button ok = views.findViewById(R.id.btn_ok);
                        Button no = views.findViewById(R.id.btn_no);
                        ImageView yz = views.findViewById(R.id.xj_yz_img);
                        Dialog dialog = builder.show();
                        UiUtils.setDialogWindowAttr(dialog, book_xj.this);
                        Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(android.R.color.transparent);
                        setImg(yz);
                        ok.setOnClickListener(view12 -> {
                            captcha = yzm.getText().toString();
                            if (captcha.length() > 0) {
                                xjData(i);
                                putxj();
                                dialog.dismiss();
                            }
                        });
                        no.setOnClickListener(view1 -> dialog.dismiss());
                    });
                    break;
                case 4:
                    viewstub_loading.setVisibility(View.GONE);
                    ToastUtil.showToast("网络 ༼ﾉ۞⌂۞༽ﾉ异常");

                    break;
                case 5:
                    viewstub_loading.setVisibility(View.GONE);
                    ToastUtil.showToast(" 数据༼ﾉ۞⌂۞༽ﾉ异常");
                    break;
                case 7:
                    viewstub_loading.setVisibility(View.GONE);
                    ToastUtil.showToast("数据༼ﾉ۞⌂۞༽ﾉ跑丢了！");
                    break;
                case 6:
                    viewstub_loading.setVisibility(View.GONE);
                    listView.setVisibility(View.GONE);
                    viewstub_null.setVisibility(View.VISIBLE);
                    break;
            }
        }
    }

}
